package com.site.wisdom_construction.util.imgUtil;

import org.apache.tomcat.util.codec.binary.Base64;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author DYF
 */
public class Base64ToOss {

    public String GenerateImage(String base64) {
        // 对字节数组字符串进行Base64解码并生成图片
        String imgStr1 = base64;
        String imgStr = imgStr1.replaceAll(" " , "+");
        //base64格式前头
        String dataPrix = "";
        //实体部分数据
        String data = "";
        // 图像数据为空
        if (imgStr == null) {
            return "添加失败,图像为空!";
        } else {
            //将字符串分成数组
            String[] d = imgStr.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                return "添加失败!";
            }
        }
        //图片后缀，用以识别哪种格式数据
        String suffix = "";
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".jpg";
        }else {
            return "添加失败,图片格式不正确!";
        }
        String dataPrixX=dataPrix+"base64,";
        String uuid = UUID.randomUUID().toString().replaceAll("-" , "");
        String tempFileName = uuid + suffix;
        //新生成的图片地址   服务器: /root/img/    本地测试: E:/test/
        String imgFilePath = "/root/img/" + tempFileName;
        //BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = Base64.decodeBase64(imgStr.replace(dataPrixX , ""));
            imgStr = imgStr.replace("base64," , "");
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    // 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            File file = new File(imgFilePath);
            try {
                //填写文件地址
                String Host = "FaceRecognition";
                //上传到OSS
                String uploadUrl = AliyunOSSUtil.upload(file, Host);
                //删除缓存文件减少储存空间
                file.delete();
                return uploadUrl;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return tempFileName;
        } catch (Exception e) {
            return "添加失败,未生成图片!";
        }
    }
}
